package com.macoli.android.permissionx.internal

import android.content.pm.PackageManager
import android.os.Bundle
import androidx.fragment.app.Fragment
import com.macoli.android.permissionx.PermissionX
import com.macoli.android.permissionx.PermissionXResult

internal typealias PermissionCallback = (granted: Boolean, resultList: List<PermissionXResult>?) -> Unit

internal class PermissionXFragment : Fragment() {

    lateinit var callback: PermissionCallback

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        val permissionList : MutableList<String> = arguments?.getStringArrayList(ARG_PERMISSION) ?: mutableListOf<String>()
        if (permissionList.isEmpty()) {
            callback(false , null)
            parentFragmentManager.beginTransaction().remove(this).commit()
            return
        }
        requestPermission(permissionList)
    }

    private fun requestPermission(permissionList: MutableList<String>) {
        val permissionsString = permissionList.joinToString(", ") // 将权限列表转换为逗号分隔的字符串
        PermissionX.log("requestPermission $permissionsString PermissionRequestFragment start request Permission")
        requestPermissions(permissionList.toTypedArray(), REQUEST_CODE_PERMISSION)
    }

    override fun onRequestPermissionsResult(
        requestCode: Int,
        permissions: Array<out String>,
        grantResults: IntArray
    ) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults)
        PermissionX.log("requestPermission onRequestPermissionsResult $requestCode , ${permissions.joinToString( ",")} , ${grantResults.joinToString(",")}")
        if (requestCode == REQUEST_CODE_PERMISSION && permissions.isNotEmpty()) {
            val permissionResultList = mutableListOf<PermissionXResult>()
            val size = permissions.size
            var allGranted = true
            for (i in 0 until size) {
                val grant = grantResults[i] == PackageManager.PERMISSION_GRANTED
                val permission = permissions[i]
                allGranted = allGranted && grant
                permissionResultList.add(PermissionXResult(permission , grant))
            }
            callback(allGranted , permissionResultList)
            PermissionX.log("requestPermission onRequestPermissionsResult callback，remove fragment")
            parentFragmentManager.beginTransaction().remove(this).commit()
        }
    }

    companion object {
        const val TAG_PERMISSION_FRAGMENT = "PermissionRequestFragment"
        const val ARG_PERMISSION = "permission"
        const val REQUEST_CODE_PERMISSION = 100
    }
}